package com.example.HeadFirstDemo.observe.selfImpl;

import lombok.ToString;

import java.util.ArrayList;

@ToString
public class MessageData implements Subject{
    private Integer id;
    private String name;
    private String address;
    /*
    实现存放观察者列表
     */
    private ArrayList<Observe> observeList;

    public MessageData() {
        this.observeList=new ArrayList<Observe>();
    }

    public MessageData(ArrayList observeList) {
        this.observeList.addAll(observeList);
    }

    public void register(Observe observe) {
        observeList.add(observe);
        System.out.println("the observe List:"+observeList);
    }

    public void unregister(Observe observe) {
        if(observeList.remove(observe)){
            System.out.println("the observe:"+observe+" is out of observeList");
            return;
        }
        System.out.println(observe+"is not in the list of observeList");
    }

    public void notifyObserve() {
        for(int count=observeList.size();count>0;count--){
            System.out.println("notfiy servce:"+observeList.get(count-1));
            observeList.get(count-1).update(this);
        }
    }

    /*
    模拟修改数据
     */
    public void setMessage(Integer id,String name,String address){
        this.id=id;
        this.name=name;
        this.address=address;
        notifyObserve();
    }
}
